#include "math_3d.h"
#define GLEW_STATIC 1
#include <GL/glew.h>
#include <glut.h>
#include "Vector2D.h"
#include "glwindow.h"
#include "shader.hpp"
#include "Clock.h"
#include "Timer.h"
#include <assert.h>
#include "config.h"

static GLuint VBO;

using Math::Vector2D;
static Vector2D shipPosition(0.0f,0.0f);
static Vector2D shipVelocity(0.0f,0.0f);



static Vector2D verts[] =
{
	Vector2D(+0.0f, +0.1f),
	Vector2D(-0.1f, -0.1f),
	Vector2D(+0.1f, -0.1f),
};
static const unsigned int NUM_VERTS =  sizeof(verts)/sizeof(verts[0]);

static void OnInitScene(void)
{
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), NULL, GL_DYNAMIC_DRAW);

}

static void OnReshapeWindow(int width,int height)
{
	glViewport(0,0,width,height);
}

static void CheckKeyState(float time)
{
	float accelration = 0.5f * time;
	if(GetAsyncKeyState(VK_UP))
		shipVelocity.y += accelration;
	if(GetAsyncKeyState(VK_DOWN))
		shipVelocity.y -= accelration;
	if(GetAsyncKeyState(VK_RIGHT))
		shipVelocity.x += accelration;
	if(GetAsyncKeyState(VK_LEFT))
		shipVelocity.x -= accelration;
    
}


static void OnUpdateScene(float time)
{
	//printf("Update %f\n",time);
	CheckKeyState(time);
	shipPosition += shipVelocity * time;

	Vector2D translatedVers[NUM_VERTS];
	//printf("%d\n",NUM_VERTS);
	//printf("Rendering ..\n");
    glClear(GL_COLOR_BUFFER_BIT);
	glPointSize(4.0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    
	for(unsigned int i=0;i<NUM_VERTS;i++)
	{
		translatedVers[i] = verts[i] + shipPosition;
	}
	glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(translatedVers),translatedVers);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);
	//glDrawArrays(GL_POINTS, 0, 3);
	//glDrawArrays(GL_LINES, 0, 4);

    glDisableVertexAttribArray(0);
    glutSwapBuffers();
}

static void OnRenderScene(void)
{
}
void GameEngine(int argc, char **argv)
{
	GLWindowCreate(1024,1024);

	SetInitSceneCallBack(OnInitScene);
	SetReshapeWindowCallBack(OnReshapeWindow);
	SetUpdateSceneCallBack(OnUpdateScene);
	SetRenderSceneCallBack(OnRenderScene);

	GLWindowStart();
}


